// pages/index.js
import {
    getNavigationbar,
} from "../../api/index.js"
import {
    downTimeFormat
} from "../../utils/util"

Page({
    /**
     * 页面的初始数据
     */
    data: {
        addStickyStyle: false,
        isLoading: false,
        swiperList: [],
        zoneList: [],
        icons: [],
        saleGoodsList: [],
        singleItemGoodsList: [],
        brandList: [],
        categoryList: [],
        goodsColumn: [],
        goodsList: [],
        goodListP: 1,
        id: '3',
        saleIndex: 0,
        navTitle: '进货商城',
        popupTitle: '配送至',
        isShow: false,
        btnText: '选择其他地址',
        tabsActive: 0,
        scrollViewHeight: 0,
        autoplay: true,
        isAhow: false,
        columnIndex: 0,
        intoView: "",
        productList: [],
        indulgenceList: [],
        activityList: [],
        dialogText: '',
        saleTime: {
            HH: 0,
            MM: 0,
            SS: 0
        },
        addressList: [],
        obj: {},
        address: "默认地址"
    },
    handleToAuth(e) {
        console.log('e', e)
    },
    onConfirms() {
        wx.navigateTo({
            url: '/pages/address_management/index',
        })
    },
    /**
     * 获取首页各种展示图
     */
    getHttpSwiperList() {
        getNavigationbar({
            act: 'banner_list',
            type: '1',
            version: '1',
        }).then(res => {
            if (res) {
                wx.nextTick(() => {
                    this.data.zoneList = []
                    this.data.activityList = []
                    console.log('广告', res)
                    res.forEach(element => {

                        if (element.id == "20") {
                            // 遍历轮播图数据，重新定义图片路径
                            element.child.forEach(items => {
                                items.thumb = getApp().globalData.http + items.thumb
                            })
                            this.setData({
                                swiperList: [...element.child]
                            })
                        } else if (element.id == "3") {
                            this.setData({
                                icons: [...element.child]
                            })
                        } else {
                            // this.data.activityList = [...new Set([...this.data.zoneList, ...element.child])] 
                            if (element.child.length > 1) {
                                element.child.pop()
                            }
                            element.child.forEach(elementj => {
                                Object.assign(elementj, {
                                    ids: element.id
                                })

                            });
                            this.setData({
                                zoneList: [...new Set([...this.data.zoneList, ...element.child, ])]
                            })
                            console.log('进', element, this.data.zoneList)
                        }
                    });
                })
            }
        })
    },

    /**
     * 首页活动商品
     */
    getHttpSaleGoodsList() {
        getNavigationbar({
            act: 'activity_index',
            lack_inventory: '1',
        }).then(res => {
            if (res) {
                let data = [];
                let product = [];
                let indulgence = [];
                wx.nextTick(() => {
                    res.forEach(element => {
                        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                            element.price = '***'
                            element.property_price= '***'
                        }
                        if (element.type == 3) {
                            data.push(element)
                            this.setData({
                                saleGoodsList: data
                            })
                        } else if (element.type == 1) {
                            product.push(element)
                            this.setData({
                                productList: product
                            })
                        } else if (element.type == 2) {
                            indulgence.push(element)
                            this.setData({
                                indulgenceList: indulgence
                            })
                        }
                    });
                })
            }
        })
    },
    /**
     * 获取单品促销数据
     */
    getHttpSingleItemGoodsList() {
        getNavigationbar({
            act: 'home_goods',
            lack_inventory: '1',
        }).then(res => {
            if (res) {
                wx.nextTick(() => {
                    console.log('崔晓', res)
                    this.setData({
                        singleItemGoodsList: res
                    })
                })
            }
        })
    },
    /**
     * 首页专区栏目
     */
    getHttpCategoryList() {
        getNavigationbar({
            act: 'district_index',
            lack_inventory: '1',
        }).then(res => {
            if (res) {
                wx.nextTick(() => {
                    res.forEach(element => {
                        element.goods.forEach(element => {
                            if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                                element.sellprice = '***'
                                element.marketprice = '***'
                            }
                        });

                        switch (element.name) {
                            case '主粮':
                                element.background = 'linear-gradient(136deg, #FAEBDE 0%, #FFFBF5 100%)';
                                element.textColor = '#B8823E';
                                break;
                            case '零食':
                                element.background = 'linear-gradient(136deg, #FFE8E8 0%, #FFEDEA 100%)';
                                element.textColor = '#823030';
                                break;
                            case '用品':
                                element.background = 'linear-gradient(136deg, #E4E5EC 0%, #F4F4F8 100%)';
                                element.textColor = '#342D42';
                                break;
                            case '营养保健':
                                element.background = 'linear-gradient(136deg, #DCEAF2 0%, #EFF4F9 100%)';
                                element.textColor = '#224063';
                                break;
                            default:
                                element.background = 'linear-gradient(136deg, #FAEBDE 0%, #FFFBF5 100%)';
                        }
                        Object.assign(element, {
                            rightIconText: '更多',
                            rightIconUrl: 'arrow',
                        });
                    });
                    this.setData({
                        categoryList: res
                    });
                });
            }
        });
    },
    /**
     * 获取品牌促销数据
     */
    getHttpbrandList() {
        getNavigationbar({
            act: 'home_brand',
        }).then(res => {
            if (res) {
                wx.nextTick(() => {
                    this.setData({
                        brandList: res
                    })
                })
            }
        })
    },
    /**
     * 底部专区列表
     */
    getHttpGoodsList() {
        getNavigationbar({
            act: 'bottom_district_list',
            lack_inventory: '',
            id: this.id || '3',
            p: this.data.goodListP
        }).then(res => {
            if (res) {
                res.forEach(element => {

                    let sellpriceInt = Math.floor(element.sellprice);
                    Object.assign(element, {
                        price: sellpriceInt
                    })
                    if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                        element.price = '***'
                    }
                });
                wx.nextTick(() => {
                    this.setData({
                        goodsList: res
                    })
                })
            }
        })
    },

    // 标签切换回调函数方法
    handleTabsChange(e) {
        const tabsData = e.detail.detail
        this.setData({
            tabsActive: tabsData.index,
            autoplay: tabsData.index == 0 ? true : false // 判断切换标签时，关闭自动轮播
        })
    },

    /**
     * 更多触发回调函数方法,跳转商品列表
     * @param {*} e 
     */
    handleMoreEntry(e) {
        const {
            name,
            value
        } = e.currentTarget.dataset
        const params = {
            name: name,
            value: value ? {
                id: value.id,
                district_id: value.district_id
            } : null
        }
        switch (name) {
            case '单品促销':
                wx.navigateTo({
                    url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
                })
                break;
            case '主粮':
                wx.navigateTo({
                    url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
                })
                break;
            case '零食':
                wx.navigateTo({
                    url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
                })
                break;
            case '用品':
                wx.navigateTo({
                    url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
                })
                break;
            case '营养保健':
                wx.navigateTo({
                    url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
                })
                break;
        }
    },

    /**
     * 商品列表分类菜单栏回调函数方法
     * @param {*} e 
     */
    onColumnTap(e) {
        this.data.goodListP = 1;
        this.id = e.currentTarget.dataset.id;
        wx.nextTick(() => {
            this.setData({
                columnIndex: e.currentTarget.dataset.value,
                intoView: "item" + e.currentTarget.dataset.value,
            })
        })
        this.data.goodListP = 1
        this.getHttpGoodsList();
    },
    /**
     * 底部专区导航栏
     */
    getGoodsColumn() {
        getNavigationbar({
            act: 'bottom_district_banner'
        }).then(res => {
            if (res) {
                res.forEach(element => {
                    Object.assign(element, {
                        topTitle: element.name,
                        btmTitle: element.tips,
                        line: "/images/line.png"
                    })
                });
                wx.nextTick(() => {
                    this.setData({
                        goodsColumn: [...res],
                    })
                })
            }
        })
    },
    /**
     * 头部导航左侧内容点击回调函数方法
     */
    onClickLeft(e) {
        console.log('e',e)
        // 此处编写请求逻辑（获取当前地址）

        this.setData({
            isShow: true
        })

        // wx.hideTabBar() // 隐藏底部导航
    },
    getAddress() {
        getNavigationbar({
            act: "addressres",
            type: "getlist",
        }).then(res => {
            if (res) {
                res.forEach(item => {
                    item.userAddress = item.province + item.city + item.county
                })
                let addr = res.find(item => item.is_default == "1")
                wx.nextTick(() => {
                    this.setData({
                        addressList: res,
                        address: addr.userAddress
                    })
                })
            }
        })
    },
    /**
     * 选择默认地址
     * @param {} e 
     */
    check(e) {
        let value = e.detail
        console.log('点击',value)
        getNavigationbar({
            act: "addressres",
            type: "editor",
            id: value.id,
            truename: value.truename,
            phone: value.phone,
            province: value.province,
            city: value.city,
            county: value.county,
            town: value.town,
            provinceId: value.provinceId,
            cityId: value.cityId,
            countyId: value.countyId,
            townId: value.townId,
            address: value.address,
            is_default: '1'
        }).then(res => {
            console.log('切换地方',res)
            if (res) {
                if (res.result == 101) {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: res.msg
                        });
                    });
                } else {
                    let title = '添加成功';
                    if (value.id) {
                        title = '编辑成功';
                    }
                    this.setData({
                        isShow: false,
                        address: e.detail.userAddress
                    })
                    wx.showTabBar()
                    this.onLoad()

                }
            }
        })


    },


    /**
     * 弹出层关闭按钮回调函数方法
     */
    onClose() {
        wx.showTabBar()
    },

    /**
     * 弹出层确认按钮回调函数方法
     */
    onConfirm() {
        wx.navigateTo({
            url: '/pages/address_management/index',
        })
    },

    /**
     * 秒杀商品轮播回调函数方法
     * @param {*} e 
     */
    saleSwiperChange(e) {
        const endTime = new Date("2024-12-31T23:59:59").getTime();
        const updateCountdown = () => {
            const now = new Date().getTime();
            const distance = endTime - now;
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            this.setData({
                saleTime: {
                    HH: hours,
                    MM: minutes,
                    SS: seconds
                }
            });
            if (distance <= 0) {
                clearInterval(interval);
            }
        };

        // 每秒更新一次倒计时
        const interval = setInterval(updateCountdown, 1000);

    },

    /**
     * 秒杀框点击触发回调函数方法
     * @param {*} e 
     */
    handleSaleChange() {
        wx.navigateTo({
            url: '/pages/mall_flash_sale/index',
        })
    },
    /**
     * 根据条件跳转各项活动专区回调函数方法
     */
    handleRegionEntry(e) {
        const {
            value
        } = e.currentTarget.dataset;
        let num = value.type
        console.log('根据条件跳转各项活动专区回调函数方法', num);
        const params = {
            name: value.name,
            value: value
        }
        // 根据类型判断跳转到具体的链接
        if (num == 1) {
            params.name = '9.8'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }
        // 根据类型判断跳转到具体的链接
        if (num == 2) {
            params.name = '特卖专区'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }

        // 根据类型及活动ID同时判断前往对应条件页
        if (num == 3 && value.activeid) {
            let obj = {
                ...value,
                type:'Issuing'
            }
            obj.name = obj.brandname
            let objStr = encodeURIComponent(JSON.stringify(obj));
            wx.navigateTo({
                url: '/pages/goods_list/index?obj=' + objStr,
            })
        }
        if (num == 7) {
            wx.navigateTo({
                url: `/pages/new_born_zone/index?data=${JSON.stringify(params)}`,
            })
        }
        // 根据类型判断前往新品专区
        if (num == 8) {
            params.name = '新品专区'
            wx.navigateTo({
                url: `/pages/goods_indulgence/index?data=${JSON.stringify(params)}`,
            })
        }
        // 根据类型判断前往一件代发
        if (num == 14) {
            let obj = {
                ...params,
                shipping: true,type:'Issuing'
            }
            let objStr = encodeURIComponent(JSON.stringify(obj));
            wx.navigateTo({
                url: '/pages/goods_list/index?obj=' + objStr,
            })
        }
        // 根据类型及活动ID同时判断前往对应条件页
        if (num == 20 && value.activeid) {
            wx.navigateTo({
                url: `/pages/goods_more_lists/index?data=${JSON.stringify(params)}`,
            })
        }
    },
    /**
     * 首页跳转商品详情页回调函数方法
     */
    handleGoodsDetail(e) {
        const {
            value
        } = e.currentTarget.dataset
        const params = {
            goodsId: "",
            area: "",
            detailType: 1,
            act: "good_detail"
        }
        if (value) {
            const {
                goodsid,
                id
            } = e.currentTarget.dataset.value
            if (goodsid) {
                params.goodsId = goodsid
            } else {
                params.goodsId = id
            }
        } else {
            const {
                id
            } = e.detail
            params.goodsId = id
        }
        wx.navigateTo({
            url: `/pages/goods_detail/index?data=${JSON.stringify(params)}`,
        })
    },

    /**
     * 跳转品牌列表页回调函数方法
     */
    handleBrandEntry(e) {
        const {
            value
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/brand_list/index?data=${JSON.stringify(value)}`,
        })
    },

    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.header').boundingClientRect()
        query.exec(res => {
            let headerHeight = res[0].height;
            let winHeight; // 窗口可使用高度
            let tabbarHeight; // 底部导航高度
            wx.getSystemInfo({
                success: (res) => {
                    winHeight = res.windowHeight
                    tabbarHeight = res.windowHeight - res.safeArea.bottom + 50 // 计算底部导航总高度比变化
                }
            })
            let scrollHeight = winHeight - headerHeight - tabbarHeight; // 滚动区域高度
            that.setData({
                scrollViewHeight: scrollHeight
            })
        })
    },

    /**
     * 下拉刷新回调函数方法
     */
    onPullDownRefresh: function () {
        // 下拉刷新逻辑
        wx.startPullDownRefresh({
            success: function () {
                console.log('1')
                // 请求数据
                // 数据请求完成后调用 wx.stopPullDownRefresh() 结束下拉刷新动作
            }
        });
    },

    onScrollToUpper: function (event) {
        console.log('2')
        // 监听用户下拉操作
        // 可以在这里添加一些下拉时的动画效果
    },


    /**
     * 组件生命周期函数，在组件实例进入页面节点树时执行
     */
    attached() {
        console.log('==')
    },
    onShareAppMessage: function () {
        return {
            title: '宠老板',
            path: '/pages/index/index', // 分享的页面路径
            imageUrl: '分享图片的链接', // 分享的图片链接
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        this.getHttpSwiperList();
        let res = wx.getStorageSync('USER')
        console.log('setStorageSync', res)
        this.data.obj = res
       
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log('===============')
        this.computeScrollViewHeight() // 调用动态计算回调方法
        this.getGoodsColumn();
        this.getHttpGoodsList();

        this.getHttpSingleItemGoodsList();
        this.getHttpbrandList();
        this.getHttpCategoryList();
        this.getHttpSaleGoodsList();
        this.getAddress()
        wx.showTabBar()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        // 监听页面轮播组件隐藏
        this.setData({
            autoplay: false
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // 监听页面轮播组件卸载
        this.setData({
            autoplay: false
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        // 下拉刷新时的逻辑处理
        console.log('下拉刷新事件触发');
        // 在这里可以编写重新请求数据等逻辑
        // 请求数据完成后记得调用wx.stopPullDownRefresh()停止下拉刷新动画
        wx.stopPullDownRefresh();
    },
    onScrollViewScroll: function (e) {
        if (e.detail.scrollTop >= 2100) { // 当滚动到200px位置时添加样式
            this.setData({
                addStickyStyle: true
            });
        } else {
            this.setData({
                addStickyStyle: false
            });
        }
        // 在这里可以处理scroll-view滚动时的逻辑
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onPullDownRefresh() {
        console.log("下拉")
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    scrollToLower() {
        this.data.goodListP++
        getNavigationbar({
            act: 'bottom_district_list',
            lack_inventory: '',
            id: this.id || '3',
            p: this.data.goodListP
        }).then(res => {

            if (res) {
                res.forEach(element => {
                    let sellpriceInt = Math.floor(element.sellprice);
                    Object.assign(element, {
                        price: sellpriceInt
                    })
                });
                const list = this.data.goodsList.concat(res)
                wx.nextTick(() => {
                    this.setData({
                        goodsList: list
                    })
                })
            }
        })
    },
})